package camid.distribution.activeobject;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;

public class ObjectScheduler {

	private String objectId;
	
	private Object entity;
	
	private ExecutorService executor;
	
	private ReadWriteLock readWriteLock;
	
	private Lock writeLock;
	private Lock readLock;
	
	public ObjectScheduler(String objectId, Object entity) {
//		this.readWriteLock = new ReentrantReadWriteLock();
//		this.readLock = readWriteLock.readLock();
//		this.writeLock = readWriteLock.writeLock();
		
		this.objectId = objectId;
		this.entity = entity;
		this.executor = Executors.newSingleThreadExecutor();
	
	}

	public ObjectScheduler(String objectId, Object entity,
			ExecutorService executor) {
		this.objectId = objectId;
		this.entity = entity;
		this.executor = executor;
	}

	public synchronized Future<?> submitTask(String method, Object[] parameters) {
		
		Future<Object> futureTask = null;
		ObjectTask task = new ObjectTask(entity, method, parameters);
		try 
		{
//			readLock.lock();
			futureTask = executor.submit(task);
		}
		catch(RejectedExecutionException e)
		{
			futureTask = null;
		}
		finally
		{
//			readLock.unlock();
		}
		return futureTask;
	}
	
	public void shutdown()
	{
		this.executor.shutdown();
	}
	
	public String getObjectId()
	{
		return this.objectId;
	}

	public Class<?> getEntityClass() 
	{	
		return entity.getClass();
	}
	
	public void setEntity(Object entity)
	{
		try 
		{
//			writeLock.lock();
			this.entity = entity;
		}
		finally
		{
//			writeLock.unlock();
		}
	}

	public Object getEntity() 
	{
		Object entity = null;
		try
		{
//			readLock.lock();
			entity = this.entity;
		}
		finally
		{
//			readLock.unlock();
		}
		return entity;
	}

}
